//起别名
typealias Velocity = Double

//增加扩展
//扩展中不能定义存储属性,可以定义计算属性
extension Velocity {
    var kph:Velocity{
        return self * 1.060934
    }
    
    var mph:Velocity{
        return self
    }
}

protocol Vehicle {
    var topSpeed:Velocity{get}
    var numberOfDoors:Int{get}
    var hasFlatbed:Bool{get}
}

struct Car {
    let make:String
    let model:String
    let year:Int
    let color:String
    let nickname:String
//    var numberOfDoors:Int
    var gasLevel:Double {
        willSet{
            precondition(newValue <= 1.0 && newValue >= 0.0, "New value must be between 0 and 1.")
        }
    }
}

//使用扩展给类型实现指定的协议
extension Car:Vehicle{
    var topSpeed: Velocity {
        return 180
    }
    
    var numberOfDoors: Int {
        return 4
    }
    
    var hasFlatbed: Bool {
        return false
    }
}

//使用扩展添加初始化方法
extension Car {
    init(make:String,model:String,year:Int) {
        self.init(make: make,
                  model: model,
                  year: year,
                  color: "Black",
                  nickname: "N/A",
                  gasLevel: 1.0)
    }
}

var byd = Car(make: "Ford", model: "Fusion", year: 2020)

//创建带嵌套类型的扩展
extension Car {
    enum Kind {
        case coupe //轿跑
        case sedan //三厢轿车
    }
    var kind:Kind{
        if numberOfDoors == 2 {
            return.coupe
        }else{
            return .sedan
        }
    }
}

byd.kind

//扩展类型中的函数
extension Car {
    mutating func emptyGas(by amount:Double){
        precondition(amount <= 1 && amount > 0, "Amount to remove must be between 0 and 1.")
        precondition(amount < gasLevel, "要放掉的油不能大于当前油量")
        gasLevel -= amount
    }
    
    mutating func fillGas(){
        gasLevel = 1.0
    }
}

byd.emptyGas(by: 0.3)
byd.gasLevel
byd.fillGas()
byd.gasLevel


//练习:扩展int类型,添加一个timesFive计算属性
extension Int{
    var timesFive: Int{
        return self*5
    }
}

5.timesFive

